package com.advertisementsystem.Exception;


import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
//@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult<?> handleBusinessException(BusinessException e) {
        // log.error("业务异常：{}", e.getMessage(), e);
        System.out.println(e);
        return ResponseResult.error(e.getResultCode().getCode(), e.getMessage());
    }

    /**
     * 参数验证失败异常处理
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    public ResponseResult<?> handleValidException(Exception e) {
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        } else {
            bindingResult = ((BindException) e).getBindingResult();
        }

        StringBuilder message = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            message.append(fieldError.getField())
                    .append(": ")
                    .append(fieldError.getDefaultMessage())
                    .append(", ");
        }
        message.delete(message.length() - 2, message.length());

        return ResponseResult.error(ResultCode.VALIDATE_FAILED.getCode(), message.toString());
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ResponseResult<?> handleNullPointerException(NullPointerException e) {
        System.out.println(e);
        return ResponseResult.error(ResultCode.SYSTEM_INNER_ERROR.getCode(), "空指针异常");
    }

    // /**
    //  * 处理其他异常
    //  */
    // @ExceptionHandler(value = Exception.class)
    // public ResponseResult<?> handleException(Exception e) {
    //     System.out.println(e);
    //     return ResponseResult.error(ResultCode.SYSTEM_INNER_ERROR.getCode(), "系统繁忙，请稍后重试");
    // }
}
